package com.feonix.common.basedao;

import java.sql.Blob;
import java.sql.Clob;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import org.springframework.jdbc.core.RowMapper;

import com.feonix.common.util.StringUtil;


public class ArrayRowMap implements RowMapper<String[]> {
	
	private ResultSetMetaData resultSetMetaData = null;

	private int columnCount = 0;

	@Override
	public String[] mapRow(ResultSet rs, int rowNum) throws SQLException {
		if (this.resultSetMetaData == null) {
			this.resultSetMetaData = rs.getMetaData();
			this.columnCount = this.resultSetMetaData.getColumnCount();
		}

		ArrayList<String> metaDataList = new ArrayList<String>();
		String str = null;
		Object obj = null;
		for (int i = 1; i <= this.columnCount; ++i) {
			str = this.resultSetMetaData.getColumnLabel(i).toLowerCase();
			if (str.indexOf(".") > -1) {
				str = str.substring(str.indexOf(".") + 1);
			}
			if ("rownum_".equals(str))
				continue;
			if ("__hibernate_row_nr__".equals(str)) {
				continue;
			}
			obj = rs.getObject(i);
			if (obj instanceof Blob)
				obj = rs.getBytes(i);
			else if (obj instanceof Clob)
				obj = rs.getString(i);
			else if (obj instanceof Boolean) {
				obj = Integer.valueOf(rs.getInt(i));
			}
			metaDataList.add(StringUtil.getString(obj));
		}
		return metaDataList.toArray(new String[metaDataList.size()]);
	}

}
